import { type PaginationProps } from "@pureadmin/table";
import { ElMessage, FormInstance, ElMessageBox } from "element-plus";
import {
  SupplierEnterpriseInfoCreate,
  SupplierEnterpriseInfoIsUnlocked,
  SupplierEnterpriseInfoGetAllByPagedAndSort,
  SupplierEnterpriseInfoDelete,
  SupplierEnterpriseInfoGetLockedInfo
} from "@/api/stu/SupplyChainFinance"
import { useRoute } from "vue-router";
import { ref, reactive, nextTick, watch, onMounted } from "vue";
import qs from "qs";
import { emitter } from "@/utils/mitt";
export function useEcommercePlatform() {
  const route = useRoute()
  const dataList = ref<any>([]);
  const loading = ref<boolean>(true);
  const DialogVisible = ref<boolean>(false);
  const RefEntryPlatform = ref()
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 20,
    currentPage: 1,
    pageSizes: [10, 20, 50, 100],
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "序号",
      type: "index",
      fixed: "left",
      minWidth: 50
    },
    {
      label: "供应商企业名称",
      prop: "supplyName",
      minWidth: 150
    },
    {
      label: "总资产(元)",
      prop: "totalAssets",
      minWidth: 150
    },
    {
      label: "总负债(元)",
      minWidth: 150,
      prop: "totalLiabilities",
    },
    {
      label: "资产负债率(%)",
      prop: "assetLiabilityRatio",
      minWidth: 150
    },
    {
      label: "净利润(元)",
      prop: "netProfit",
      minWidth: 150
    },
    {
      label: "营业总收入(元)",
      prop: "totalRevenue",
      minWidth: 150
    },
    {
      label: "营业利润(元)",
      prop: "operatingProfit",
      minWidth: 150
    },
    {
      label: "利润总额(元)",
      prop: "totalProfit",
      minWidth: 150
    },
    {
      label: "净现金流(元)",
      prop: "netCashFlow",
      minWidth: 150
    },
    {
      label: "经营性净现金流占比(%)",
      prop: "percentageNetOperatingCashFlow",
      minWidth: 150
    },
    {
      label: "经营性现金流量净额(元)",
      prop: "netOperatingCashFlow",
      minWidth: 150
    },
    {
      label: "净资产收益率(%)",
      prop: "returnOnEquity",
      minWidth: 150
    },
    {
      label: "营业总支出(元)",
      prop: "totalOperatingExpenditure",
      minWidth: 150
    },
    {
      label: "货币资金(亿元)",
      prop: "monetaryFunds",
      minWidth: 150
    },
    {
      label: "应收账款(元)",
      prop: "accountsReceivable",
      minWidth: 150
    },
    {
      label: "应付账款(元)",
      prop: "accountsPayable",
      minWidth: 150
    },
    {
      label: "预收账款(元)",
      prop: "accountsReceivedAdvance",
      minWidth: 150
    },
    {
      label: "净利润同比(%)",
      prop: "netProfitYearOnYear",
      minWidth: 150
    },
    {
      label: "营业总收入同比(%)",
      prop: "totalOperatingIncome",
      minWidth: 150
    },
    {
      label: "净现金流同比增长(%)",
      prop: "netCashFlowGrowth",
      minWidth: 150
    },
    {
      label: "状态",
      prop: "netCashFlowGrowth",
      fixed: "right",
      width: 100,
      cellRenderer: ({ row }) => (
        <el-tag type={
          row.isActive ? "success" : ""}>
          {
            row.isActive ? "已锁定" : "未锁定"
          }
        </el-tag>
      )
    },
    {
      label: "操作",
      fixed: "right",
      width: 200,
      slot: "operation"
    }
  ];
  const EntryPlatform = reactive({
    name: "",
    TotalAssets: "",
    TotalLiabilities: "",
    AssetliabilityRatio: "",
    NetProfit: "",
    GrossPperatingIncome: "",
    OperatingProfit: "",
    GrossProfit: "",
    NetCashFlow: "",
    PONOCashFlow: "",
    NOCashFlow: "",
    ReturnEquity: "",
    GrossOperatingExpenditure: "",
    Monetaryfunds: "",
    AccountsReceivable: "",
    AccountsPayable: "",
    AccountsReceivedAdvance: "",
    NetprofitYearOYear: "",
    TotalOperatingIYOY: "",
    NetCashFlowIYOY: ""
  })
  // 万亿 长度 14
  const rules: any = {
    name: [
      {
        required: true,
        validator: (rule: any, value: string, callback: () => void) => {
          if (value.length <= 7 || !value.includes('有限公司')) {
            return callback(new Error('名称最少八个字并以有限公司结尾'))
          } else {
            return callback();
          }
        },
      }
      // { required: true, message: '请输入供应商企业名称', trigger: 'blur' },
      // { min: 8, message: '名称长度不能低于8个字符', trigger: 'change' }
    ],
    TotalAssets: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 50000000000000) {
            return callback(new Error('输入总资产金额，不大于50万亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ],
    TotalLiabilities: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 50000000000000) {
            return callback(new Error('输入总负债金额，不大于50万亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }
    ],
    NetProfit: [
      {
        required: true, type: 'number',
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 10000000000 || value < -5000000000) {
            return callback(new Error('范围：负50亿-100亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur'
      }

    ],
    GrossPperatingIncome: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 1000000000000 || value < 0) {
            return callback(new Error('范围：0-1万亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    OperatingProfit: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < -10000000000 || value > 1000000000000) {
            return callback(new Error('范围：负100亿-10000亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    GrossProfit: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < -10000000000 || value > 1000000000000) {
            return callback(new Error('范围：负100亿-10000亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    NetCashFlow: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < -1000000000000 || value > 1000000000000) {
            return callback(new Error('范围：负10000亿-10000亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    PONOCashFlow: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < -100000 || value > 100000) {
            return callback(new Error('范围：负100000%-100000%'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    NOCashFlow: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < -100000000000 || value > 100000000000) {
            return callback(new Error('范围：负1000亿-10000亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    ReturnEquity: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < -10 || value > 20) {
            return callback(new Error('范围：负10%-20%'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    GrossOperatingExpenditure: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 1000000000000 || value < 0) {
            return callback(new Error('范围：0-10000亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    Monetaryfunds: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 1000000000000 || value < 0) {
            return callback(new Error('范围：0-10000亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    AccountsReceivable: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 1000000000000 || value < 0) {
            return callback(new Error('范围：0-10000亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    AccountsPayable: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 1000000000000 || value < 0) {
            return callback(new Error('范围：0-10000亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    AccountsReceivedAdvance: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value > 1000000000000 || value < 0) {
            return callback(new Error('范围：0-10000亿'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    NetprofitYearOYear: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (value < -100000 || value > 100000) {
            return callback(new Error('范围：负100000%-100000%'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    TotalOperatingIYOY: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < -10000 || value > 10000) {
            return callback(new Error('范围：负10000%-10000%'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ],
    NetCashFlowIYOY: [
      {
        required: true, min: 14,
        validator: (rule: any, value: number, callback: () => void) => {
          if (typeof value == 'string' || value < -1000000 || value > 1000000) {
            return callback(new Error('范围：负10000%-10000%'))
          } else {
            return callback();
          }
        },
        trigger: 'blur',
      }
    ]
  };

  function SubtimEntryPlatform(row: FormInstance | undefined) {
    (row as any).validate(async valid => {
      if (!valid) return;
      console.log(EntryPlatform);
      const data = {
        SupplyName: EntryPlatform.name,//供应商名称
        TotalAssets: EntryPlatform.TotalAssets || 0,//总资产(元)
        Totalliabilities: EntryPlatform.TotalLiabilities || 0,//总负债(元)
        AssetLiabilityRatio: EntryPlatform.AssetliabilityRatio || 0,//资产负债率(%)
        NetProfit: EntryPlatform.NetProfit || 0,//净利润(元)
        TotalRevenue: EntryPlatform.GrossPperatingIncome || 0,//营业总收入(元)
        OperatingProfit: EntryPlatform.OperatingProfit || 0,//营业利润(元)
        TotalProfit: EntryPlatform.GrossProfit || 0,//利润总额(元)
        NetCashFlow: EntryPlatform.NetCashFlow || 0,//净现金流(元)
        PercentageNetOperatingCashFlow: EntryPlatform.PONOCashFlow || 0,//:经营性净现金流占比(%)
        NetOperatingCashFlow: EntryPlatform.NOCashFlow || 0,//经营性现金流量净额(元)
        ReturnOnEquity: EntryPlatform.ReturnEquity || 0,//净资产收益率(%) 
        TotalOperatingExpenditure: EntryPlatform.GrossOperatingExpenditure || 0,//营业总支出(元)
        MonetaryFunds: EntryPlatform.Monetaryfunds || 0,//货币资金(元)
        AccountsReceivable: EntryPlatform.AccountsReceivable || 0,//:应收账款(元)
        AccountsPayable: EntryPlatform.AccountsPayable || 0,//应付账款(元)
        AccountsReceivedAdvance: EntryPlatform.AccountsReceivedAdvance || 0,//预收账款(元)
        NetProfitYearOnYear: Number(EntryPlatform.NetprofitYearOYear) || 0,//净利润同比(%)
        TotalOperatingIncome: EntryPlatform.TotalOperatingIYOY || 0,//营业总收入同比(%)
        NetCashFlowGrowth: EntryPlatform.NetCashFlowIYOY || 0,//净现金流同比增长(%)
        planId: route.query.planId,
        taskId: route.query.taskId
      };
      const res = await SupplierEnterpriseInfoCreate(data);
      if (res.success) {
        ElMessage.success(res.msg)
        CloseEntryPlatform(row);
        getSupplierEnterpriseInfoGetAllByPagedAndSort()
      } else {
        ElMessage.error(res.msg)
      }
    })
  }

  function CloseEntryPlatform(row: FormInstance | undefined) {
    row.resetFields();
    DialogVisible.value = false;
  }

  async function getSupplierEnterpriseInfoGetAllByPagedAndSort() {
    const res = await SupplierEnterpriseInfoGetAllByPagedAndSort({
      taskId: route.query.taskId,
      planId: route.query.planId,
      pageIndex: pagination.currentPage,
      pageCount: pagination.pageSize
    });
    if (res.success) {
      dataList.value = res.data.items;
      loading.value = false;
      pagination.total = res.data.totalCount;
    } else {
      ElMessage.error(res.msg);
      setTimeout(() => { loading.value = false; }, 1500)
    }
  }

  async function UnlockFirm(row: any) {
    const data = qs.stringify({
      id: row.seiId,
      taskId: route.query.taskId,
      planId: route.query.planId,
      isActive: true
    })
    const res = await SupplierEnterpriseInfoIsUnlocked(data);
    if (res.success) {
      ElMessage.success(res.msg);
      const data = {
        taskId: route.query.taskId,
        planId: route.query.planId,
      }
      let res1 = await SupplierEnterpriseInfoGetLockedInfo(data)
      if (res1.data) {
        sessionStorage.setItem("seiId", res1.data?.seiId)
      }
      getSupplierEnterpriseInfoGetAllByPagedAndSort();
      emitter.emit('refresSupplier')
    } else {
      ElMessage.error(res.msg);
    }
  }

  async function deleteSupple(row) {
    ElMessageBox({
      title: '提示', //MessageBox 标题
      closeOnClickModal: false,
      message: `是否确认删除${row.supplyName}?`, //MessageBox 消息正文内容
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      // 确定
      const data = qs.stringify({
        id: row.seiId,
      })
      const res = await SupplierEnterpriseInfoDelete(data);
      if (res.success) {
        ElMessage.success(res.msg);
        getSupplierEnterpriseInfoGetAllByPagedAndSort();
      } else {
        ElMessage.error(res.msg);
      }
    }).catch(() => { })
  }

  onMounted(() => {
    getSupplierEnterpriseInfoGetAllByPagedAndSort()
  })

  function handleSizeChange() {
    getSupplierEnterpriseInfoGetAllByPagedAndSort()
  }
  function handleCurrentChange() {
    getSupplierEnterpriseInfoGetAllByPagedAndSort()
  }
  watch(() => EntryPlatform.TotalAssets, (newValue, oldValue) => {
    // 在这里处理属性值变化的逻辑
    EntryPlatform.AssetliabilityRatio = Number(((EntryPlatform.TotalLiabilities / EntryPlatform.TotalAssets) * 100).toFixed(2))

  });
  watch(() => EntryPlatform.TotalLiabilities, (newValue, oldValue) => {
    // 在这里处理属性值变化的逻辑
    EntryPlatform.AssetliabilityRatio = Number(((EntryPlatform.TotalLiabilities / EntryPlatform.TotalAssets) * 100).toFixed(2))
  });
  return {
    rules,
    columns,
    loading,
    dataList,
    pagination,
    handleSizeChange,
    handleCurrentChange,
    DialogVisible,
    EntryPlatform,
    RefEntryPlatform,
    UnlockFirm,
    CloseEntryPlatform,
    SubtimEntryPlatform,
    deleteSupple
  }
}
